package com.yuyang.wifi.utils;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Window;

import com.yuyang.wifi.MyApplication;


public class ScreenUtils {
	private static int screenHeight;
	private static int screenWidth;
	private static int height9;
	private static float density;
	private static int statusHeight;

	private static void calculateScreen() {
		DisplayMetrics metrics = MyApplication.getApp().getResources().getDisplayMetrics();
		screenHeight = metrics.heightPixels;
		screenWidth = metrics.widthPixels;
		height9 = 9 * screenWidth / 16;
		density = metrics.density;
	}

	public static int getScreenHeight() {
		if (screenHeight == 0) {
			calculateScreen();
		}
		return screenHeight;
	}

	public static int getScreenWidth() {
		if (screenWidth == 0) {
			calculateScreen();
		}
		return screenWidth;
	}

	public static int getHeight9() {
		if (height9 == 0) {
			calculateScreen();
		}
		return height9;
	}

	public static float getDensity() {
		if (density == 0)
			calculateScreen();
		return density;
	}

	public static int dp2px(Context ctx, float dp) {
		final float scale = ctx.getResources().getDisplayMetrics().density;
		return (int) (dp * scale + 0.5f);
	}

	public static int px2dp(Context ctx, float px) {
		final float scale = ctx.getResources().getDisplayMetrics().density;
		return (int) (px / scale + 0.5f);
	}

	/**
	 * 将sp值转换为px值，保证文字大小不变
	 *
	 * @param spValue （DisplayMetrics类中属性scaledDensity）
	 * @return
	 */
	public static int sp2px(Context ctx, float spValue) {
		final float fontScale = ctx.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}


	public static int getStatusHeight(Window window) {
		if (statusHeight == 0) {
			calculateStatusHeight(window);
		}
		return statusHeight;
	}

	private static void calculateStatusHeight(Window window) {
		//获取status_bar_height资源的ID
		int resourceId = window.getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			//根据资源ID获取响应的尺寸值
			statusHeight = window.getContext().getResources().getDimensionPixelSize(resourceId);
		}
		if (statusHeight == 0) {
			try {
				Class<?> clazz = Class.forName("com.android.internal.R$dimen");
				Object object = clazz.newInstance();
				int height = Integer.parseInt(clazz.getField("status_bar_height")
						.get(object).toString());
				statusHeight = window.getContext().getResources().getDimensionPixelSize(height);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
